// 全局模拟chrome扩展API
const chrome = {
  runtime: {
    onMessage: {
      addListener: jest.fn(),
      removeListener: jest.fn(),
    },
    sendMessage: jest.fn((msg, callback) => {
      chrome.runtime.onMessage.mockListeners.forEach((listener) =>
        listener(msg, {}, callback)
      );
    }),
  },
  storage: {
    local: {
      set: jest.fn((obj, callback) => callback && setTimeout(callback, 0)),
      get: jest.fn().mockImplementation((key, callback) => {
        setTimeout(() => callback({ wal: ['video3'] }), 0);
      }),
      remove: jest.fn((keys, callback) => callback && setTimeout(callback, 0)),
    },
  },
  downloads: {
    download: jest.fn(),
  },
  system: {
    memory: {
      getInfo: jest.fn().mockImplementation((cb) =>
        cb({
          availableCapacity: 100,
          capacity: 1024,
          percentUsed: 9.7,
        })
      ),
    },
  },
};

global.performance.memory = {};
Object.defineProperty(global.performance.memory, 'usedJSHeapSize', {
  get: jest.fn(() => performance.memory.usedJSHeapSize || 0),
  set: jest.fn((value) => (performance.memory.usedJSHeapSize = value)),
  configurable: true,
});

// 添加消息模拟触发机制
chrome.runtime.onMessage = {
  mockListeners: [],
  addListener: jest.fn(function (cb) {
    this.mockListeners.push(cb);
  }),
  removeListener: jest.fn(function (cb) {
    const index = this.mockListeners.indexOf(cb);
    if (index > -1) this.mockListeners.splice(index, 1);
  }),
  mockSendMessage: function (msg) {
    this.mockListeners.forEach((listener) => listener(msg));
  },
};

global.chrome = chrome;
global.crypto = {
  getRandomValues: jest.fn((arr) =>
    arr.map(() => Math.floor(Math.random() * 256))
  ),
  subtle: {
    generateKey: jest.fn((algorithm, extractable, keyUsages) =>
      Promise.resolve({
        algorithm,
        extractable,
        keyUsages,
      })
    ),
    encrypt: jest.fn().mockImplementation((algorithm, key, data) => {
      return Promise.resolve(new ArrayBuffer(data.byteLength));
    }),
    decrypt: jest.fn().mockImplementation((algorithm, key, data) => {
      return Promise.resolve(new ArrayBuffer(data.byteLength));
    }),
  },
  getRandomValues: jest.fn((arr) =>
    arr.map(() => Math.floor(Math.random() * 256))
  ),
};
